define(function(require, exports) {
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var $	= require('jquery');
	var util = require('util');
	var Drop = require('@base/common/drop').drop;

	// 频次控制
	var Base = view.container.extend({
		init: function(config) {
			var self = this;
			config = pubjs.conf(config, {
				 'class': 'M-PageFrequency',
				 'isCampaign': true,
				 'isSingle': false,
				 'view_model': {
					'view': {
						type1: true
						,type2: true
					}
				 },
				 'opts':null
			});

			self.Super('init', arguments);
		},
		afterBuild: function() {
			var tpl = [
				'<div class="mb5" ms-class="dn: !view.type1">',
					'<span class="M-PageFrequencyType mr10" pub-name="type1" pub-mod="@base/common/drop.drop"/>',
					'<span class="M-PageFrequencyInterval mr10" pub-name="interval1" pub-mod="@base/common/drop.drop"/>',
					'<span class="M-PageFrequencyInput mr5" pub-name="input1" pub-mod="@base/common/input.text"/>',
					'<span class="M-PageFrequencyAfterText">' + LANG('次') + '</span>',
				'</div>',
				'<div class="mb5" ms-class="dn: !view.type2">',
					'<span class="M-PageFrequencyType mr10" pub-name="type2" pub-mod="@base/common/drop.drop"/>',
					'<span class="M-PageFrequencyInterval mr10" pub-name="interval2" pub-mod="@base/common/drop.drop"/>',
					'<span class="M-PageFrequencyInput mr5" pub-name="input2" pub-mod="@base/common/input.text"/>',
					'<span class="M-PageFrequencyAfterText">' + LANG('次') + '</span>',
				'</div>'
			].join('');
			this.append(tpl);
			var cfg = this.getConfig();

			if(cfg.isSingle)
			{
				this.vm.$.view.type1 = false;
			}

			var items = [
				{name: LANG('创意包'), id: 3},
				{name: LANG('活动'), id: 0}
			];

			var isCampaign = cfg.isCampaign;
			var productRight = isCampaign ? 'campaign.frequencyProduct' : 'user.frequencyProduct';
			if(pubjs.checkRight(productRight))
			{
				items.push({name: LANG('产品'), id: 1}); // todo 产品的Id待定。
			}

			var period_items = [
				{name: LANG('每小时'), id: 1},
				{name: LANG('每天'), id: 2},
				{name: LANG('每周'), id: 0},
				{name: LANG('每月'), id: 3}
			];

			var halfYearRight = isCampaign ? 'campaign.frequencyHalfYear' : 'user.frequencyHalfYear';
			if(pubjs.checkRight(halfYearRight))
			{
				period_items.push({name: LANG('半年'), id: 4});
			}

			if(!cfg.opts){
				cfg.opts = {
					type1: {
						'options': items,
						'width': 120,
						'def': LANG('选择对象'),
						'hasSearch': false
					},
					type2: {
						'options': items.concat([
							{name: LANG('选择对象'), id: null}
						]),
						'width': 120,
						'def': LANG('选择对象'),
						'hasSearch': false
					},
					interval1: {
						'options': period_items,
						'width': 120,
						'def': LANG('选择单位'),
						'hasSearch': false
					},
					interval2: {
						'options': period_items.concat([{name: LANG('选择单位'), id:null}]),
						'width': 120,
						'def': LANG('选择单位'),
						'hasSearch': false
					},
					input1: {
						width: 100
					},
					input2: {
						width: 100
					}
				}
			}

			this.buildFromTemplate(cfg.opts);
		},
		afterBuildTemplate: function() {
			this.reset();
		},
		getData: function() {
			var data = [];
			var self = this;

			var i, row;
			if(self.getConfig('isSingle'))
			{
				row = {};
				// 类型选择
				row.Type = self.get('type2').getValue('id');
				// 频率选择
				row.Period = self.get('interval2').getValue('id');
				// 频率
				row.Frequency = self.get('input2').getValue();

				return row;
			}

			for(i = 1; i <= 2; i++){
				row = {};
				// 类型选择
				row.Type = self.get('type' + i).getValue('id');
				// 频率选择
				row.Period = self.get('interval' + i).getValue('id');
				// 频率
				row.Frequency = self.get('input' + i).getValue();

				if(row.Type === null || row.Period === null || row.Frequency === ''){

				}else{
					data.push(row);
				}
			}

			return data;
		},
		setData: function(data) {
			var self = this;

			if(self.getConfig('isSingle'))
			{
				self.get('type2').setValue(data["Type"]);
				self.get('interval2').setValue(data["Period"]);
				self.get('input2').setValue(data["Frequency"]);
			}
			else
			{
				if (data) {
					if (data[0]) {
						self.get('type1').setValue(data[0]["Type"]);
						self.get('interval1').setValue(data[0]["Period"]);
						self.get('input1').setValue(data[0]["Frequency"]);
					}
					if (data[1]) {
						self.get('type2').setValue(data[1]["Type"]);
						self.get('interval2').setValue(data[1]["Period"]);
						self.get('input2').setValue(data[1]["Frequency"]);
					}
				}
			}


			return self;
		},
		reset: function() {
			var self = this;
			// 第一列要设置默认值
			// 类型选择
			self.get('type1').setValue(3);
			// 频率选择
			self.get('interval1').setValue(2);
			// 频率
			self.get('input1').setValue(6);

			// 类型选择
			self.get('type2').reset();
			// 频率选择
			self.get('interval2').reset();
			// 频率
			self.get('input2').setValue('');

			return self;
		}
	});

	exports.base = Base;


	// 尝试用新vm的v-hook修改了一个版本
	var base_item = {
		'type': 4,
		'period': 1,
		'frequency': '',
		'showDelete': false
	};

	var Multi = view.container.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				'class': 'M-PageFrequency',
				'isCampaign': true,
				'isSingle': false,
				'vModel':
				{
					'items': [util.extend({'guid': util.guid()}, base_item)]
				},
				'vMethods':
				{
					'evRemove': this.evRemove,
					'evAdd': this.evAdd
				},
				'vHooks':
				{
					'afterAppend': this.afterAppend,
					'beforeRemove': this.beforeRemove
				},
				type_options: [],
				period_options: []
			});

			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			var el = this.getDOM();
			var tpl = $([
				'<div>',
					'<div class="mb5" v-for="item in items" v-hook:after="afterAppend">',
						'<span class="M-PageFrequencyType mr10 type"/>',
						'<span class="M-PageFrequencyInterval mr10 period"/>',
						'<span class="M-PageFrequencyInput mr5"><input class="w120" type="text" v-model="item.frequency"/></span>',
						'<span class="M-PageFrequencyAfterText">' + LANG('次') + '</span>',

						'<a class="ml15" v-show="item.showDelete" v-on:click="evRemove($index, item.guid)">'+ LANG('删除') +'</a>',
					'</div>',
					'<div class="mt10"><a class="" v-on:click="evAdd">'+ LANG('添加频次控制') +'</a></div>',
				'</div>'
			].join('')).appendTo(el);

			this.buildFromTemplate({

			});
			this.vm.mount();
		},
		afterAppend: function(el, index)
		{
			var items = this.vm.getCopy('items');
			var item = items[index];
			var type_el = $(el).find('.type');
			var period_el = $(el).find('.period');

			var type_name = 'type_' + item.guid;
			var period_name = 'period_' + item.guid;

			var type_mod = this.get(type_name);
			var period_mod = this.get(period_name);

			// 如果模块存在先销毁，暴力解决重复创建的问题
			if (type_mod)
			{
				type_mod.destroy();
			}
			if (period_mod)
			{
				period_mod.destroy();
			}

			this.create(type_name, Drop, {
				'target': type_el,
				'hasSearch': false,
				'width': 120,
				'def': LANG('选择对象'),
				'options': this.getConfig('type_options'),
				'value': item.type
			});
			this.create(period_name, Drop, {
				'target': period_el,
				'hasSearch': false,
				'width': 120,
				'def': LANG('选择单位'),
				'options': this.getConfig('period_options'),
				'value': item.period
			});
		},
		evRemove: function(index, guid)
		{
			var items = this.vm.$.items;
			items.splice(index, 1);

			var type_mod = this.$['type_' + guid];
			var period_mod = this.$['period_' + guid];

			// 删除类型模块
			if (type_mod)
			{
				type_mod.destroy();
			}

			// 删除频次模块
			if (period_mod)
			{
				type_mod.destroy();
			}

			this.updateDelete();
		},
		evAdd: function()
		{
			var item = util.extend({'guid': util.guid()}, base_item);
			var items = this.vm.$.items;
			if (items.length >= 6)
			{
				pubjs.alert(LANG('最多添加6条记录'));
				return false;
			}

			items.push(item);

			this.updateDelete();
		},
		updateDelete: function()
		{
			var items = this.vm.$.items;
			var showDelete = (items.length > 1);

			util.each(items, function(item)
			{
				item.showDelete = showDelete;
			});
		},
		setData: function(data)
		{
			var self = this;
			var items = this.vm.$.items;
			data = util.clone(data || []);

			util.each(data, function(item, index)
			{
				var row = items[index] || {};
				// 初始化数据
				row.showDelete = false;
				row.guid = util.guid();

				// 业务数据
				row.type = item.Type;
				row.period = item.Period;
				row.frequency = item.Frequency;

				items.$set(index, row);
			});

			this.updateDelete();
			return this;
		},
		getData: function()
		{
			var items = this.vm.getCopy('items');
			var data = [];
			var self = this;

			util.each(items, function(item)
			{
				var guid = item.guid;

				var row = {};
				row.Type = +self.get('type_' + guid).getValue('id');
				// 频率选择
				row.Period = +self.get('period_' + guid).getValue('id');
				// 频率
				row.Frequency = +item.frequency || 0;

				data.push(row);
			});

			return data;
		},
		reset: function()
		{
			this.vm.reset();
			return this;
		}
	});
	exports.multi = Multi;

	var Plan = Multi.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				type_options: [
					{name: LANG('创意包'), id: 3},
					{name: LANG('活动'), id: 0},
					{name: LANG('计划'), id: 4}
				],
				period_options: [
					{name: LANG('每小时'), id: 1},
					{name: LANG('每天'), id: 2},
					{name: LANG('每周'), id: 0},
					{name: LANG('每月'), id: 3},
					{name: LANG('每半年'), id: 4},
				]
			});

			this.Super('init', arguments);
		}
	});
	exports.plan = Plan;
});